<template>
  <div class="todo-container">
    <h3>基于localStorage存储状态、使用pubsub-js订阅者-发布者通信</h3>
    <div class="todo-wrap">
      <!--<TodoHeader @addTodo="addTodo"/>-->
      <TodoHeader ref="header"/>
      <TodoList :todos="todos"/>
      <TodoFooter :todos="todos" :deleteCompleteTodos="deleteCompleteTodos" :selectAll="selectAll"/>
    </div>
  </div>
</template>

<script>
import TodoHeader from '../components/todo2/TodoHeader.vue'
import TodoList from '../components/todo2/TodoList.vue'
import TodoFooter from '../components/todo2/TodoFooter.vue'
import storageUtils from '../utils/storageUtils'
import PubSub from 'pubsub-js'

export default {
  data () {
    return {
      todos: storageUtils.readTodos()
    }
  },

  mounted () {
    // 绑定自定义事件(addTodo)监听
    // this.$on('addTodo',  this.addTodo) 绑定监听的目标不对
    this.$refs.header.$on('addTodo', this.addTodo)
    // 订阅消息(deleteTodo)
    PubSub.subscribe('deleteTodo', (msg, index) => {
      this.deleteTodo(index)
    })
  },

  methods: {
    addTodo (todo) {
      this.todos.unshift(todo)
    },

    deleteTodo (index) {
      this.todos.splice(index, 1)
    },

    // 删除所有已完成的
    deleteCompleteTodos () {
      this.todos = this.todos.filter(todo => !todo.complete)
    },

    // 全选/全不选
    selectAll (isSelectAll) {
      this.todos.forEach(todo => {
        todo.complete = isSelectAll
      })
    }
  },

  watch: {
    todos: {
      deep: true,
      handler: storageUtils.saveTodos
    }
  },

  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  }
}
</script>

<style>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
